package com.xingyang;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * 游戏开始前的玩家选择对话框，允许用户选择2-4名玩家参与游戏
 */
public class PlayerSelectionDialog extends JDialog {
    
    private int selectedPlayerCount = 2; // 默认为2名玩家
    private Color[] playerColors;
    private String[] playerNames;
    private boolean selectionConfirmed = false;
    
    private JSpinner playerCountSpinner;
    private JPanel playerConfigPanel;
    private JTextField[] nameFields;
    private JButton[] colorButtons;
    
    /**
     * 创建玩家选择对话框
     * @param parent 父窗口
     */
    public PlayerSelectionDialog(Frame parent) {
        super(parent, "선수 선택 (选择玩家)", true);
        
        // 初始化颜色和名称数组
        playerColors = new Color[]{
            new Color(220, 50, 50),   // 红色
            new Color(50, 100, 220),  // 蓝色
            new Color(50, 180, 50),   // 绿色
            new Color(200, 150, 50)   // 黄色
        };
        
        playerNames = new String[]{"Player 1", "Player 2", "Player 3", "Player 4"};
        nameFields = new JTextField[4];
        colorButtons = new JButton[4];
        
        initComponents();
        updatePlayerConfig();
        
        // 设置对话框属性
        setSize(450, 500);
        setResizable(false);
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
    /**
     * 初始化对话框组件
     */
    private void initComponents() {
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout(10, 15));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        mainPanel.setBackground(new Color(240, 240, 220));
        
        // 标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        JLabel titleLabel = new JLabel("윷놀이 게임 설정 (game setting)", JLabel.CENTER);
        titleLabel.setFont(new Font("SansSerif", Font.BOLD, 24));
        titleLabel.setForeground(new Color(139, 69, 19));
        titlePanel.add(titleLabel, BorderLayout.CENTER);
        
        // 玩家数量选择面板
        JPanel countPanel = new JPanel();
        countPanel.setOpaque(false);
        countPanel.setBorder(new EmptyBorder(10, 0, 10, 0));
        JLabel countLabel = new JLabel("선수 수 (player count):");
        countLabel.setFont(new Font("SansSerif", Font.BOLD, 14));
        
        SpinnerNumberModel model = new SpinnerNumberModel(2, 2, 4, 1);
        playerCountSpinner = new JSpinner(model);
        playerCountSpinner.setFont(new Font("SansSerif", Font.PLAIN, 14));
        ((JSpinner.DefaultEditor)playerCountSpinner.getEditor()).getTextField().setEditable(false);
        
        playerCountSpinner.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                selectedPlayerCount = (Integer) playerCountSpinner.getValue();
                updatePlayerConfig();
            }
        });
        
        countPanel.add(countLabel);
        countPanel.add(playerCountSpinner);
        
        // 玩家配置面板 - 使用带滚动的面板以适应任意数量的玩家
        playerConfigPanel = new JPanel();
        playerConfigPanel.setLayout(new GridLayout(0, 1, 0, 10));
        playerConfigPanel.setOpaque(false);
        playerConfigPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(new Color(139, 69, 19)),
            "선수 설정 (player setting)",
            0,
            0,
            new Font("SansSerif", Font.BOLD, 14),
            new Color(139, 69, 19)
        ));
        
        // 创建玩家配置行
        for (int i = 0; i < 4; i++) {
            JPanel playerRow = createPlayerConfigRow(i);
            playerConfigPanel.add(playerRow);
        }
        
        // 中央内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(0, 15));
        contentPanel.setOpaque(false);
        contentPanel.add(countPanel, BorderLayout.NORTH);
        contentPanel.add(playerConfigPanel, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonPanel.setOpaque(false);
        JButton startButton = new JButton("게임 시작 (game start)");
        startButton.setFont(new Font("SansSerif", Font.BOLD, 16));
        startButton.setBackground(new Color(100, 180, 100));
        startButton.setForeground(Color.WHITE);
        startButton.setFocusPainted(false);
        startButton.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.DARK_GRAY, 1),
            BorderFactory.createEmptyBorder(10, 20, 10, 20)
        ));
        
        // 按钮点击事件
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 保存玩家名称
                for (int i = 0; i < selectedPlayerCount; i++) {
                    String name = nameFields[i].getText().trim();
                    if (!name.isEmpty()) {
                        playerNames[i] = name;
                    }
                }
                selectionConfirmed = true;
                dispose();
            }
        });
        
        JButton cancelButton = new JButton("취소 (取消)");
        cancelButton.setFont(new Font("SansSerif", Font.BOLD, 16));
        cancelButton.setBackground(new Color(180, 100, 100));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setFocusPainted(false);
        cancelButton.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.DARK_GRAY, 1),
            BorderFactory.createEmptyBorder(10, 20, 10, 20)
        ));
        
        // 按钮点击事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectionConfirmed = false;
                dispose();
            }
        });
        
        buttonPanel.add(startButton);
        buttonPanel.add(cancelButton);
        
        // 添加到主面板
        mainPanel.add(titlePanel, BorderLayout.NORTH);
        mainPanel.add(contentPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    /**
     * 创建每个玩家的配置行
     */
    private JPanel createPlayerConfigRow(final int playerIndex) {
        JPanel row = new JPanel(new BorderLayout(10, 0));
        row.setOpaque(false);
        
        // 玩家标签
        JLabel playerLabel = new JLabel("선수 " + (playerIndex + 1) + " (player " + (playerIndex + 1) + "):");
        playerLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
        
        // 名称输入框
        nameFields[playerIndex] = new JTextField(playerNames[playerIndex]);
        nameFields[playerIndex].setPreferredSize(new Dimension(150, 25));
        
        // 颜色选择按钮
        colorButtons[playerIndex] = new JButton("");
        colorButtons[playerIndex].setBackground(playerColors[playerIndex]);
        colorButtons[playerIndex].setPreferredSize(new Dimension(25, 25));
        colorButtons[playerIndex].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Color selectedColor = JColorChooser.showDialog(
                    PlayerSelectionDialog.this,
                    "선수 " + (playerIndex + 1) + " 색상 선택 (choose color)",
                    playerColors[playerIndex]
                );
                
                if (selectedColor != null) {
                    playerColors[playerIndex] = selectedColor;
                    colorButtons[playerIndex].setBackground(selectedColor);
                }
            }
        });
        
        // 添加组件到行
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        inputPanel.setOpaque(false);
        inputPanel.add(nameFields[playerIndex]);
        inputPanel.add(colorButtons[playerIndex]);
        
        row.add(playerLabel, BorderLayout.WEST);
        row.add(inputPanel, BorderLayout.CENTER);
        
        return row;
    }
    
    /**
     * 根据选择的玩家数量更新配置面板
     */
    private void updatePlayerConfig() {
        // 启用/禁用相应的玩家配置行
        for (int i = 0; i < 4; i++) {
            boolean enabled = i < selectedPlayerCount;
            nameFields[i].setEnabled(enabled);
            colorButtons[i].setEnabled(enabled);
            nameFields[i].getParent().getParent().setVisible(enabled);
        }
        
        // 重新布局并调整对话框大小
        int newHeight = 300 + (selectedPlayerCount * 50);
        setSize(450, newHeight);
        
        revalidate();
        repaint();
    }
    
    /**
     * 显示对话框并返回选择结果
     * @return 如果用户确认选择返回true，否则返回false
     */
    public boolean showDialog() {
        setVisible(true);
        return selectionConfirmed;
    }
    
    /**
     * 获取选择的玩家数量
     */
    public int getPlayerCount() {
        return selectedPlayerCount;
    }
    
    /**
     * 获取玩家颜色
     */
    public Color[] getPlayerColors() {
        return playerColors;
    }
    
    /**
     * 获取玩家名称
     */
    public String[] getPlayerNames() {
        return playerNames;
    }
} 